// components/home/index.js
import {
  request
} from '../../api/index'
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';

import {
  formatTime
} from '../../utils/util';
import {
  searchData,
  numSettingsType
} from '../../dataSource'
import {
  updateStatus
} from '../../api/collection_record'

let dialog;
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    root: {
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    refresh: false,
    onLoading: false,
    dataSource: [],
    popupShow: false,
    type: numSettingsType.RECORD,
    // statusObj: {},
    // statusPickerShow: false,
    searchData,
    // options: [{
    //     text: '未完成',
    //     value: 0,
    //     color: '#1989fa'
    //   },
    //   {
    //     text: '已完成',
    //     value: 1,
    //     color: '#07c160'
    //   },
    //   {
    //     text: '已作废',
    //     value: 2,
    //     color: '#ff976a'
    //   },
    //   {
    //     text: '不限',
    //     value: '',
    //     color: 'rgba(0, 0, 0, 0.35)'
    //   }
    // ],
    page: {

      currentPage: 1,
      size: 7
    },
    total: 50,
    remark: '',
    id: '',
    status: [],
    recipeData: [],
    search: {
      picker: false
    },
    expand: false,
    selectedIds: []
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onRefresh() {
      this.setData({
        refresh: true,
        page: {
          ...this.data.page,
          currentPage: 1,
          ...this.data.searchData
        }
      })
      this.fetchData();
      setTimeout(() => {
        this.setData({
          refresh: false
        })
      }, 1200)
    },
    onRefreshEnd() {},
    onRemove(event) {
      const id = event.detail,
        dataSource = this.data.dataSource;
      const newDataSource = dataSource.filter(it => it.id !== id);
      this.setData({
        dataSource: newDataSource,
        selectedIds: this.data.selectedIds.filter(it => it !== id)
      })

    },
    onRemoveAll(event) {
      const ids = event.detail,
        dataSource = this.data.dataSource;
      const newDataSource = dataSource.filter(it => {
        return !ids.includes(it.id)
      });

      this.setData({
        dataSource: newDataSource,
        selectedIds: []
      })

    },
    toggleSelected() {

      this.setData({
        expand: !this.data.expand
      })
    },
    onScrollLoad() {
      if (this.data.total > this.data.dataSource.length) {
        this.setData({
          onLoading: true,
          page: {
            ...this.data.page,
            currentPage: this.data.page.currentPage + 1
          }
        })
        this.loadData();
        setTimeout(() => {
          this.setData({
            onLoading: false
          })
        }, 1200)
      }
    },

    loadData() {
      request.collectionRecord({
        ...this.data.page,
        status: this.data.status,
        ...this.data.searchData
      }, (e) => {
        const data = e?.records.map(item => {
          return {
            ...item,
            time: this.formatTime(item.createTime)
          }
        })
        this.setData({
          dataSource: [...this.data.dataSource, ...data],
          total: e.total,
          page: {
            ...this.data.page,
            currentPage: e.current
          }
        })
      }, function (e) {
        Toast({
          message: e,
          position: 'bottom'
        });
      })
    },

    setPageProperty() {
      wx.setNavigationBarTitle({
        title: '采集列表'
      })
    },
    fetchData() {
      if (!this.data.refresh) {
        wx.showLoading({
          title: '加载中'
        });
        setTimeout(() => {
          wx.hideLoading();
        }, 600);
      }
      request.collectionRecord({
        ...this.data.page,
        status: this.data.status,
        ...this.data.searchData
      }, (e) => {
        const data = e?.records.map(item => {
          return {
            ...item,
            time: this.formatTime(item.createTime)
          }
        })
        this.setData({
          dataSource: data,
          total: e.total,
          page: {
            ...this.data.page,
            currentPage: e.current
          }
        })
      }, function (e) {
        Toast({
          message: e,
          position: 'bottom'
        });
      })
    },
    edditHandle(event) {
      wx.navigateTo({
        url: `../navigation/index?id=${event.currentTarget.dataset.source.id}`
      })
    },
    formatTime(time) {
      const t = time.replace(/-/g, '/');
      const d = new Date(t);
      return formatTime(d);
    },
    onAdd() {
      wx.redirectTo({
        url: '/pages/add-record/index',
      })
    },

    onStatusChange(event) {
      const status = event.detail;

      const page = Object.assign({}, this.data.page, {

        currentPage: 1
      })
      this.setData({
        page,
        status: status || status === 0 ? [status] : []
      })

      this.fetchData();
    },
    setStatePass(event) {
      const id = event.detail;
      wx.showModal({
        content: '是否把此记录的状态变更为[已完成]？',
        success: res => {
          if (res.confirm) {
            updateStatus({
              id
            }, () => {
              const dataSource = this.data.dataSource.map(it => {
                if (it.id === Number(id)) {
                  return {
                    ...it,
                    status: 1
                  }
                }
                return it;
              });
              this.setData({
                dataSource
              })
            })
          }
        }
      })
    },
    onSearch(event) {
      const value = event.detail;
      this.setData({
        page: {
          ...this.data.page,
          currentPage: 1
        },
        searchData: value
      })
      this.fetchData();
    },

    popupOpen(event) {
      this.setData({
        popupShow: true,
      })
      const {
        remark,
        id,
        glazeId
      } = event.currentTarget.dataset.item || {};
      this.setData({
        remark,
        id
      })
      if (glazeId) {
        request.glazeList({
          collectionRecordIds: id,
          sortNumber: 0
        }, (e) => {
          request.glazeList({
            collectionRecordIds: id,
            sortNumber: 1
          }, (res) => {
            this.setData({
              recipeData: [e[0]?.performanceResult?.recipe, res[0]?.performanceResult?.recipe]
            })
          })
        })
      }
    },
    popupClose() {
      this.setData({
        popupShow: false
      })
    },

    showSearch(event) {
      this.setData({
        search: {
          ...this.data.search,
          picker: true
        }
      })

    },
    hideSearch(event) {
      this.setData({
        search: {
          ...this.data.search,
          picker: false
        }
      })

    },
    toggleSearch() {
      this.data.search.picker ? this.hideSearch() : this.showSearch()
    },
    onSelected(event) {
      this.setData({
        selectedIds: event.detail
      })
    }
  },
 
  lifetimes: {
    attached: function () {
      // 在组件实例进入页面节点树时执行
      wx.onAppRoute((res) => {
        if (res.path === 'pages/index/index' && res.openType === 'navigateBack') {
          this.setPageProperty();
          this.setData({
            page: {
              ...this.data.page,
              currentPage: 1
            }
          })
          this.fetchData();
        }
      })
      this.setPageProperty();
      this.fetchData();
        

    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },
})